package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.Trie;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.mapper.ApAssociateWordsMapper;
import com.heima.search.service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class ApAsscociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements ApAssociateWordsService {


    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.执行分页查询
        if(dto.getPageSize()>10){
            dto.setPageSize(10);
        }

        LambdaQueryWrapper<ApAssociateWords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(ApAssociateWords::getAssociateWords, dto.getSearchWords()); //模糊查询
        lambdaQueryWrapper.orderByDesc(ApAssociateWords::getCreatedTime);//按照时间倒排


        Page<ApAssociateWords> page = new Page(dto.getPageNum(), dto.getPageSize());
        this.page(page, lambdaQueryWrapper);

        //3.响应数据
        ResponseResult responseResult = new PageResponseResult(dto.getPageNum(), dto.getPageSize(), (int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult searchV2(UserSearchDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.从redis查询联想词列表数据
        String key = "asscociate_list";
        String asscociateListJson = stringRedisTemplate.opsForValue().get(key);//查询到联想词列表JSO字符串
        List<ApAssociateWords> apAssociateWordsList = JSON.parseArray(asscociateListJson, ApAssociateWords.class);


        //3.如果没有数，就从mysql查询，再存入redis
        if(apAssociateWordsList==null || apAssociateWordsList.size()==0){
            apAssociateWordsList = list();
            
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(apAssociateWordsList));
        }


        //4.遍历联想词列表，将数据初始化到trie树中
        Trie trie = new Trie();
        for (ApAssociateWords apAssociateWords : apAssociateWordsList) {
            trie.insert(apAssociateWords.getAssociateWords());
        }


        //5.将搜索关键词到trie匹配，得到匹配结果
        List<String> matchAsscociateWordsList = trie.startWith(dto.getSearchWords());


        //6.遍历匹配结果，将数据封装响应
        List<Map> mapList = new ArrayList<>();
        if(matchAsscociateWordsList!=null && matchAsscociateWordsList.size()>0){
            for (String associateWords : matchAsscociateWordsList) {
                //将每一个字符串类型的联想词，转为map对象

                Map map = new HashMap<>(); //匹配的联想词对象
                map.put("associateWords", associateWords);

                mapList.add(map);
            }
        }

        return ResponseResult.okResult(mapList);
    }
}
